package jmine.tec.performance.test;

import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Timer;

/**
 * Gatherer of information regarding memory usage of a test, apllication, etc.
 * 
 * @author joao.enomoto
 */
public class MemoryDataCollector implements DataCollector {

    private static final int SECONDS = 2;

    private Timer memoryTimer;

    private Map<String, MemoryMonitor> memoryUsageValues;

    private MemoryMonitor memoryMonitor;

    /**
     * Constructor.
     */
    public MemoryDataCollector() {
        this.memoryUsageValues = new HashMap<String, MemoryMonitor>();
    }

    /**
     * {@inheritDoc}
     */
    public void startCollect(String name) {
        this.memoryMonitor = new MemoryMonitor();
        this.memoryTimer = new Timer();
        this.memoryTimer.schedule(this.memoryMonitor, SECONDS * 1000, SECONDS * 1000);
    }

    /**
     * {@inheritDoc}
     */
    public void stopCollect(String name) {
        this.memoryTimer.cancel();
        this.memoryUsageValues.put(this.strip(name), this.memoryMonitor);
    }

    /**
     * {@inheritDoc}
     */
    public Properties getResultAsProperties() {
        Properties properties = new Properties();
        for (String testName : memoryUsageValues.keySet()) {
            properties.setProperty(testName + ".memory.max", this.getMaxOfMemoryUsage(testName));
            properties.setProperty(testName + ".memory.mean", this.getMeanOfMemoryUsage(testName));
        }
        return properties;
    }

    /**
     * @param name inspected application name.
     * @return mean of memory usage for that application.
     */
    private String getMeanOfMemoryUsage(String name) {
        return String.valueOf(memoryUsageValues.get(name).getMeanOfMemoryUsage());
    }

    /**
     * @param name inspected application name.
     * @return max of memory usage for that application.
     */
    private String getMaxOfMemoryUsage(String name) {
        return String.valueOf(memoryUsageValues.get(name).getMaxMemoryUsage());
    }

    /**
     * @param name application name.
     * @return stripped application name.
     * @deprecated shouldn't be used, looking for a better place to normalize this name.
     */
    @Deprecated
    private String strip(String name) {
        return name.replaceAll("(\\.| |%20)", "_");
    }

}
